import { login } from '@/services/ant-design-pro/api';
import {
    AlipayOutlined,
    LockOutlined,
    MobileOutlined,
    TaobaoOutlined,
    UserOutlined,
    WeiboOutlined,
} from '@ant-design/icons';
import {
    LoginFormPage,
    ProConfigProvider,
    ProFormCaptcha,
    ProFormCheckbox,
    ProFormText,
} from '@ant-design/pro-components';
import { Link, useIntl, useModel, useRequest, history } from '@umijs/max';
import { Alert, Button, Col, Divider, Form, Input, Popover, Progress, Row, Select, Space, Tabs, message, theme } from 'antd';
import type { CSSProperties } from 'react';
import { useEffect, useState } from 'react';
import { flushSync } from 'react-dom';
import useStyles from './style.style';
import { Store } from 'antd/es/form/interface';
import { StateType, fakeRegister, sendCode } from './service';

type LoginType = 'phone' | 'account';

const iconStyles: CSSProperties = {
    color: 'rgba(0, 0, 0, 0.2)',
    fontSize: '18px',
    verticalAlign: 'middle',
    cursor: 'pointer',
};


const FormItem = Form.Item;
const { Option } = Select;

const passwordProgressMap: {
    ok: 'success';
    pass: 'normal';
    poor: 'exception';
} = {
    ok: 'success',
    pass: 'normal',
    poor: 'exception',
};

const LoginMessage: React.FC<{
    content: string;
}> = ({ content }) => {
    return (
        <Alert
            style={{
                marginBottom: 24,
            }}
            message={content}
            type="error"
            showIcon
        />
    );
};

const CodeButton = ({ form, sendCodeRun }: any) => {
    const { styles } = useStyles();
    const [count, setCount]: [number, any] = useState(0);
    let interval: number | undefined;

    const onGetCaptcha = async () => {
        const values = await form.validateFields(['captcha', 'phone'])
        if (!values.captcha) {
            return
        }
        await sendCodeRun({ captcha: values.captcha, to: values.phone })
        let counts = 59;
        setCount(counts);
        interval = window.setInterval(() => {
            counts -= 1;
            setCount(counts);
            if (counts === 0) {
                clearInterval(interval);
            }
        }, 1000);
    };

    useEffect(
        () => () => {
            clearInterval(interval);
        },
        [interval],
    );

    return <Button
        size="large"
        disabled={!!count}
        className={styles.getCaptcha}
        onClick={onGetCaptcha}
    >
        {count ? `${count} s` : '获取验证码'}
    </Button>
}

const Page = () => {
    const { token } = theme.useToken();
    const { styles } = useStyles();
    const [open, setVisible]: [boolean, any] = useState(false);
    const [prefix, setPrefix]: [string, any] = useState('86');
    const [time, setTime] = useState(Date.now())
    const confirmDirty = false;

    const { run: sendCodeRun } = useRequest<{
        data: StateType;
    }>(sendCode, {
        manual: true,
    });

    const passwordStatusMap = {
        ok: (
            <div className={styles.success}>
                <span>强度：强</span>
            </div>
        ),
        pass: (
            <div className={styles.warning}>
                <span>强度：中</span>
            </div>
        ),
        poor: (
            <div className={styles.error}>
                <span>强度：太短</span>
            </div>
        ),
    };

    const [form] = Form.useForm();

    const getPasswordStatus = () => {
        const value = form.getFieldValue('password');
        if (value && value.length > 9) {
            return 'ok';
        }
        if (value && value.length > 5) {
            return 'pass';
        }
        return 'poor';
    };
    const { loading: submitting, run: register } = useRequest<{
        data: any;
    }>(fakeRegister, {
        manual: true,

        onSuccess: (data, params) => {
            if (data) {
                message.success('注册成功！');
                history.push({
                    pathname: `/user/register-result?account=${params[0].phone}`,
                });
            }
        },
    });
    const checkConfirm = (_: any, value: string) => {
        const promise = Promise;
        console.log(form.getFieldValue('pwd'));

        if (value && value !== form.getFieldValue('pwd')) {
            return promise.reject('两次输入的密码不匹配!');
        }
        return promise.resolve();
    };
    const checkPassword = (_: any, value: string) => {
        const promise = Promise;
        // 没有值的情况
        if (!value) {
            setVisible(true);
            return promise.reject('请输入密码!');
        } else {
            // 有值的情况
            if (value.length < 6) {
                setVisible(true);
                return promise.reject('');
            }
            setVisible(false);
            if (value && confirmDirty) {
                form.validateFields(['confirm']);
            }
        }
        return promise.resolve();
    };
    const changePrefix = (value: string) => {
        setPrefix(value);
    };
    const renderPasswordProgress = () => {
        const value = form.getFieldValue('password');
        const passwordStatus = getPasswordStatus();
        return value && value.length ? (
            <div className={styles[`progress-${passwordStatus}`]}>
                <Progress
                    status={passwordProgressMap[passwordStatus]}
                    strokeWidth={6}
                    percent={value.length * 10 > 100 ? 100 : value.length * 10}
                    showInfo={false}
                />
            </div>
        ) : null;
    };

    const PhoneNode = ({
        onChange,
        value
    }: any) => {
        return <Space.Compact style={{ width: '100%' }}>
            <Select
                size="large"
                value={prefix}
                onChange={changePrefix}
                style={{
                    width: '30%',
                }}
            >
                <Option value="86">+86</Option>
                <Option value="87">+87</Option>
            </Select>

            <Input size="large" placeholder="手机号" onChange={onChange} value={value} />
        </Space.Compact>
    }

    return (
        <div
            style={{
                backgroundColor: 'white',
                height: '100vh',
            }}
        >
            <LoginFormPage
                form={form}
                backgroundImageUrl="https://mdn.alipayobjects.com/huamei_gcee1x/afts/img/A*y0ZTS6WLwvgAAAAAAAAAAAAADml6AQ/fmt.webp"
                //   logo="https://github.githubassets.com/images/modules/logos_page/Octocat.png"
                backgroundVideoUrl="https://gw.alipayobjects.com/v/huamei_gcee1x/afts/video/jXRBRK_VAwoAAAAAAAAAAAAAK4eUAQBr"
                title="华湘"
                containerStyle={{
                    backgroundColor: 'rgba(0, 0, 0,0.65)',
                    backdropFilter: 'blur(4px)',
                }}
                subTitle="重塑硬件数据价值，动态致胜"
                activityConfig={{
                    style: {
                        boxShadow: '0px 0px 8px rgba(0, 0, 0, 0.2)',
                        color: token.colorTextHeading,
                        borderRadius: 8,
                        backgroundColor: 'rgba(255,255,255,0.25)',
                        backdropFilter: 'blur(4px)',
                    },
                    title: '重构硬件数据边界，激发动态潜能',
                    subTitle: '华湘科技技术研讨会',

                    action: (
                        <Button
                            size="large"
                            style={{
                                borderRadius: 20,
                                background: token.colorBgElevated,
                                color: token.colorPrimary,
                                width: 120,
                            }}
                        >
                            去看看
                        </Button>
                    ),
                }}
                initialValues={{
                    headImg: 'https://mdn.alipayobjects.com/huamei_gcee1x/afts/img/A*y0ZTS6WLwvgAAAAAAAAAAAAADml6AQ/fmt.webp',
                    phone: '19938570370',
                    pwd: '123456',
                    confirm: '123456',
                    mail: '295755973@qq.com',
                    username: 'xxx',
                    code: '12345',
                }}
                onFinish={async (values) => {
                    // console.log(111);
                    await register(values);

                    // await handleSubmit(values as API.LoginParams);
                }}
                submitter={{
                    render: () => <></>
                }}
            >
                <h3>注册</h3>
                <FormItem
                    name="mail"
                    rules={[
                        {
                            required: true,
                            message: '请输入邮箱地址!',
                        },
                        {
                            type: 'email',
                            message: '邮箱地址格式错误!',
                        },
                    ]}
                >
                    <Input size="large" placeholder="邮箱" />
                </FormItem>
                <Popover
                    getPopupContainer={(node) => {
                        return document.body
                    }}
                    content={
                        open && (
                            <div
                                style={{
                                    padding: '4px 0',
                                }}
                            >
                                {passwordStatusMap[getPasswordStatus()]}
                                {renderPasswordProgress()}
                                <div
                                    style={{
                                        marginTop: 10,
                                    }}
                                >
                                    <span>请至少输入 6 个字符。请不要使用容易被猜到的密码。</span>
                                </div>
                            </div>
                        )
                    }
                    overlayStyle={{
                        width: 240,
                    }}
                    placement="right"
                    open={open}
                >
                    <FormItem
                        name="pwd"
                        className={
                            form.getFieldValue('pwd') &&
                            form.getFieldValue('pwd').length > 0 &&
                            styles.password
                        }
                        rules={[
                            {
                                validator: checkPassword,
                            },
                        ]}
                    >
                        <Input size="large" type="password" placeholder="至少6位密码，区分大小写" />
                    </FormItem>
                </Popover>
                <FormItem
                    name="confirm"
                    rules={[
                        {
                            required: true,
                            message: '确认密码',
                        },
                        {
                            validator: checkConfirm,
                        },
                    ]}
                >
                    <Input size="large" type="password" placeholder="确认密码" />
                </FormItem>
                {/* 图形验证码 */}
                <Row gutter={8}>
                    <Col span={16}>
                        <FormItem
                            name="captcha"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入图形验证码!',
                                },
                            ]}
                        >
                            <Input size="large" placeholder="验证码" />
                        </FormItem>
                    </Col>
                    <Col span={8}>
                        <a onClick={() => {
                            setTime(Date.now())
                        }}>
                            <img width={104} height={40} src={`http://127.0.0.1:8888/extra-server/api/notify/v1/captcha?time=${time}`} />
                        </a>
                    </Col>
                </Row>
                <FormItem
                    name="phone"
                    rules={[
                        {
                            required: true,
                            message: '请输入手机号!',
                        },
                        {
                            pattern: /^\d{11}$/,
                            message: '手机号格式错误!',
                        },
                    ]}
                >
                    <PhoneNode />
                </FormItem>

                {/* 手机验证码 */}
                <Row gutter={8}>
                    <Col span={16}>
                        <FormItem
                            name="code"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入验证码!',
                                },
                            ]}
                        >
                            <Input size="large" placeholder="验证码" />
                        </FormItem>
                    </Col>
                    <Col span={8}>
                        <CodeButton form={form} sendCodeRun={sendCodeRun} />
                    </Col>
                </Row>
                <FormItem>
                    <div className={styles.footer}>
                        <Button
                            size="large"
                            loading={submitting}
                            className={styles.submit}
                            type="primary"
                            htmlType="submit"
                        >
                            <span>注册</span>
                        </Button>
                        <Link to="/user/login">
                            <span>使用已有账户登录</span>
                        </Link>
                    </div>
                </FormItem>
            </LoginFormPage>
        </div>
    );
};

export default () => {
    return (
        <ProConfigProvider dark>
            <Page />
        </ProConfigProvider>
    );
};
